package com.jr.controller;

/**
 * @Function：
 * @Author 梁明哲
 * @Email 424577090@qq.com
 * @Package ${PACKAGE_NAME}
 * @Project InvoiceManage
 * @Date 2023-02-20 09:42:31
 */

import com.alibaba.fastjson.JSON;
import com.jr.entity.User;
import com.jr.service.UserService;
import com.jr.service.impl.UserServiceImpl;
import com.jr.util.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("*.do")
@MultipartConfig
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        String methodName = servletPath.substring(servletPath.lastIndexOf("/") + 1,servletPath.length() - 3);
        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        PrintWriter out = response.getWriter();
        String username =request.getParameter("account");
        String password = request.getParameter("password");
        User user = new User(username,password);
        try {
            User login = userService.login(user);
            if(login!=null){
                request.getSession().setAttribute("creatorId",login.getId());
                request.getSession().setAttribute("enterpriseId",login.getEnterpriseId());
                out.write(JSON.toJSONString(new Message(200,"登录成功!")));
            }else{
                out.write(JSON.toJSONString(new Message(201,"账号或者密码错误!")));
            }
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            out.close();
        }
    }
}
